package com.仿netty底层实现;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.concurrent.atomic.AtomicInteger;

// 不用队列，直接用wakeup()，这个方法比较特殊，如果先调用了wakeup()，则后面调用selector()时不会阻塞，有点像发放了一个许可证
public class MultiThreadServer2 {
	
	public static void main(String[] args) throws IOException {
		Thread.currentThread().setName("boss");
		ServerSocketChannel ssc=ServerSocketChannel.open();
		ssc.configureBlocking(false);
		Selector boss = Selector.open();
		SelectionKey bossKey = ssc.register(boss, 0, null);
		bossKey.interestOps(SelectionKey.OP_ACCEPT);
		ssc.bind(new InetSocketAddress(8080));
		// 1、创建固定数量的worker
		Worker[] workers = new Worker[2];
		for (int i = 0; i < workers.length; i++) {
			workers[i] = new Worker("worker-" + i);
		}
		AtomicInteger index = new AtomicInteger();
		while(true){
			boss.select();
			Iterator<SelectionKey> iter = boss.selectedKeys().iterator();
			while (iter.hasNext()){
				SelectionKey key = iter.next();
				iter.remove();
				if(key.isAcceptable()) {
					SocketChannel sc = ssc.accept();
					sc.configureBlocking(false);
					System.out.println("connected..." + sc.getRemoteAddress());
					// 2、关联selector
					System.out.println("before register..." + sc.getRemoteAddress());
					workers[index.getAndIncrement() % workers.length].register(sc);
					System.out.println("after register..." + sc.getRemoteAddress());
				}
			}
		}
	}
	
	static class Worker implements Runnable{
		private Thread thread;
		private Selector selector;
		private String name;
		private volatile boolean start = false; // 还未初始化
		
		public Worker(String name){
			this.name = name; 
		}
		
		// 初始化线程和selector
		public void register(SocketChannel sc) throws IOException {
			if(!start) {
				selector = Selector.open();
				thread = new Thread(this, name);
				thread.start();
				start = true;
			}
			// 唤醒selector方法
			selector.wakeup();
			sc.register(selector, SelectionKey.OP_READ, null);
		}
		
		@Override
		public void run(){
			while(true) {
				try {
					// 注意select()和上面往这个selector注册register Channel的顺序问题，如果先调用select()方法，会导致该selector一直阻塞，进而之后往这个
					// selector上注册 Channel的方法一直执行不了，解决办法就是queue加task，加wakeup()
					selector.select();
					Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
					while (iter.hasNext()){
							SelectionKey key=iter.next();
							iter.remove();
							if(key.isReadable()) {
								ByteBuffer buffer = ByteBuffer.allocate(16);
								SocketChannel channel = (SocketChannel)key.channel();
								System.out.println("read..." + channel.getRemoteAddress());
								channel.read(buffer);
								buffer.flip();
								// 输出buffer
							}
					}
				} catch(IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

}
